package com.chixing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chixing.entity.*;
import com.chixing.entity.VO.myCouponDetailVO;
import com.chixing.mapper.*;
import com.chixing.service.IMyorderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author smith
 * @since 2025-09-22
 */
@Service
public class MyorderServiceImpl implements IMyorderService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private MycouponMapper mycouponMapper;
    @Autowired
    private CouponMapper couponMapper;
    @Autowired
    private ReceiveAddressMapper receiveAddressMapper;
    @Autowired
    private MyorderMapper myorderMapper;
    @Autowired
    private FlowMapper flowMapper;

    @Override
    public Result getById(Integer orderId) {
        Myorder myorder = myorderMapper.selectById(orderId);
        if (myorder!=null)
            return Result.getSuccess(myorder);
        return Result.getFail(myorder);
    }

    @Override
    public Result getProductMyCouponAddress(Integer userId, Integer proId) {
        //1.查商品详情
        Product product = productMapper.selectById(proId);

        if (product!=null){
            //2.查询当前用户的优惠券
            List<myCouponDetailVO> myCouponDetailVOList = new ArrayList<>();
            QueryWrapper<Mycoupon> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId).eq("mycoupon_status",0); // 0：有效优惠券，未使用
            List<Mycoupon> mycouponList = mycouponMapper.selectList(wrapper);

            for(Mycoupon mycoupon:mycouponList){
                Coupon coupon = couponMapper.selectById(mycoupon.getCouId());
                myCouponDetailVO myCouponDetailVO  = new myCouponDetailVO();
                myCouponDetailVO.setCoupon(coupon);
                myCouponDetailVO.setMycoupon(mycoupon);
                myCouponDetailVOList.add(myCouponDetailVO);
            }

            //2.查地址
            QueryWrapper<ReceiveAddress> receiveAddressWrapper = new QueryWrapper<>();
            receiveAddressWrapper.eq("user_id",userId).eq("addr_status",0);
            List<ReceiveAddress> addressList = receiveAddressMapper.selectList(receiveAddressWrapper);
            //封装到map
            HashMap<String, Object> map = new HashMap<>();
            map.put("product",product);
            map.put("myCouponDetailVOList",myCouponDetailVOList);
            map.put("addressList",addressList);
            return Result.getSuccess(map);
        }
        return Result.getFail(null);
    }

    @Override
    public Result save(Myorder myorder) {
        myorder.setOrderNum(UUID.randomUUID().toString().replace("-",""));
        myorder.setOrderStatus(0);
        myorder.setOrderCreateTime(LocalDateTime.now());
        int rows = myorderMapper.insert(myorder);
        if (rows>0)
            return Result.saveSuccess(myorder);
        return Result.saveFail(null);
    }

    @Override
    public Result updateStatus(Integer myOrderId, Integer myOrderStatus) {
        UpdateWrapper<Myorder> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id",myOrderId).set("order_status",myOrderStatus);
        int rows = myorderMapper.update(updateWrapper);
        if (rows>0)
            return Result.updateSuccess(myOrderId);
        return Result.updateFail(null);
    }

    @Override
    public Result getByOrderNumber(String orderNum) {
        QueryWrapper<Myorder> wrapper = new QueryWrapper<>();
        wrapper.eq("order_num",orderNum);
        Myorder myorder = myorderMapper.selectOne(wrapper);
        if (myorder!=null)
            return Result.getSuccess(myorder);
        return Result.getFail(null);
    }

    @Override
    public Result getOrderDetail(Integer orderId) {
        Map<String, Object> map = new HashMap<>();
        // 1. 订单 myorder (有商品快照)
        Myorder myorder = myorderMapper.selectById(orderId);
        map.put("orderId",orderId);
        map.put("orderNumber",myorder.getOrderNum());
        map.put("orderPrice",myorder.getOrderPrice());
        map.put("orderCreateTime",myorder.getOrderCreateTime());
        map.put("orderStatus",myorder.getOrderStatus());
        map.put("productName",myorder.getProductName());
        map.put("productPrice",myorder.getProductPrice());
        map.put("productImg",myorder.getProductImg());
        //2.收件地址 receiveAddress
        ReceiveAddress receiveAddress = receiveAddressMapper.selectById(myorder.getAddressId());
        if (receiveAddress != null){
            String addressInfo = receiveAddress.getAddrProvince()+receiveAddress.getAddrCity()+receiveAddress.getAddrArea()+receiveAddress.getAddrDetail();
            map.put("addressInfo",addressInfo);
            map.put("receiveUsername",receiveAddress.getReceiveUsername());
            map.put("receiveUserTelno",receiveAddress.getReceiveUserTelno());
        }
        //3. 优惠券 mycoupon + coupon
        if (myorder.getMycouponId() != null){
            Mycoupon mycoupon = mycouponMapper.selectById(myorder.getMycouponId());
            if (mycoupon != null){
                Coupon coupon = couponMapper.selectById(mycoupon.getCouId());
                map.put("couponName",coupon.getCouName());
                map.put("couponPrice",coupon.getCouMoney());
            }
        }
        if (myorder.getOrderStatus() == 1){
            QueryWrapper<Flow> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",myorder.getOrderId());
            Flow flow = flowMapper.selectOne(wrapper);
            map.put("flowNUm",flow.getFlowNum());
            map.put("paidPrice",flow.getPaidPrice());
            map.put("paidTime",flow.getCreateTime());
        }

        return Result.getSuccess(map);
    }

    @Override
    public Result getByPageAndStatus(Integer userId, Integer orderStatus, Integer pageNUmber) {
        //将最后查到的结果放到集合中
        ArrayList<Map<String , Object>> resultList = new ArrayList<>();
        //查询语句，如果orderStatus为空就查全部
        QueryWrapper<Myorder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        if (orderStatus != null)
            wrapper.eq("order_status",orderStatus);
        wrapper.orderByDesc("order_create_time");
        //设置分页
        Page<Myorder> page = new Page<>(pageNUmber, 5);
        page = myorderMapper.selectPage(page,wrapper);
        //如果能查到数据，就要将page中的数据替换掉
        if (page.getTotal()>0){
            List<Myorder> myorderList = page.getRecords();
            for (Myorder myorder : myorderList) {
                Result orderDetailResult = this.getOrderDetail(myorder.getOrderId());
                Map<String,Object> map = (Map<String,Object>) orderDetailResult.getData();
                resultList.add(map);
            }

           Page<Map<String , Object>> resultPage =  new Page<>();
            resultPage.setCurrent(page.getCurrent());
            resultPage.setPages(page.getPages());
            resultPage.setSize(page.getSize());
            resultPage.setTotal(page.getTotal());

            resultPage.setRecords(resultList);
            return Result.getSuccess(resultPage);
        }
        return Result.getFail(null);
    }
}
